package com.ebt.m.customer.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.net.json.CustomerNoteDetailJson;
import com.ebt.m.customer.net.json.CustomerNoteJson;
import com.ebt.m.customer.net.json.CustomerTapeJson;
import com.ebt.m.customer.ui.ActivityCustomerNote;
import com.ebt.m.customer.util.AttachmentUtil;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.DisplayUtil;
import com.ebt.m.customer.util.RecordManager;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.customer.view.RecorderWrapper;
import com.ebt.m.customer.view.TapeMessageView;
import com.ebt.m.data.bean.BeanCustomerTape;
import com.ebt.m.data.entity.EntityCustomerNote;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.homepage.CustomerEvent;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.utils.JsonUtil;
import com.ebt.m.widget.MDEBTDialog;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class AdapterCustomerNote extends BaseAdapter implements OnLongClickListener {

    private List<CustomerNoteJson> mNotes;
    private LayoutInflater inflater;
    private Context mContext;
    private RecordManager mRecordManager;
    private HashMap<String, ArrayList<BeanCustomerTape>> uuidAndTapes = new HashMap<>();
    private RecorderWrapper mRecorderWrapper;
    private String mCustomerUuid;

    public AdapterCustomerNote(Context context, List<CustomerNoteJson> notes, String customerUuid) {
        this.mContext = context;
        this.mNotes = notes;
        getTheFirstPositions(mNotes);
        this.inflater = LayoutInflater.from(context);
        mRecordManager = RecordManager.getInstance();
        mRecordManager.setAppContext((AppContext) mContext.getApplicationContext());
        mRecorderWrapper = RecorderWrapper.getInstance();
        mCustomerUuid = customerUuid;
    }

    //Integer位置 Date整月
    private HashMap<Integer, Date> posAndMonth = new HashMap<Integer, Date>();

    private void getTheFirstPositions(List<CustomerNoteJson> notes) {
        if (notes == null) {
            return;
        }
        int size = notes.size();
        Date preDate;
        Date curDate;
        for (int i = 0; i < size; i++) {
            curDate = new Date(notes.get(i).lastActiveTime2);
            if (i == 0) {
                posAndMonth.put(i, curDate);
            } else {
                preDate = new Date(notes.get(i - 1).lastActiveTime2);
                //中间差了一个月以上了，需要加入posAndMonth
                if ((preDate.getYear() != curDate.getYear()) || (preDate.getMonth() != curDate.getMonth())) {
                    posAndMonth.put(i, curDate);
                }
            }
        }
    }

    @Override
    public int getCount() {
        return mNotes.size();
    }

    @Override
    public Object getItem(int position) {
        return mNotes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        CustomerNoteJson item = mNotes.get(position);

        JsonUtil.parseObjectToJsonWithTag(item);

        ViewHolder viewHolder;
        if (null == convertView) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.view_customer_item_note, parent, false);
            viewHolder.sort_title_tv = (TextView) convertView.findViewById(R.id.sort_title_tv);
            viewHolder.customer_note_item_rl_bound = (RelativeLayout) convertView.findViewById(R.id.customer_note_item_rl_bound);
            viewHolder.customer_note_item_description = (TextView) convertView.findViewById(R.id.customer_note_item_description);
            viewHolder.customer_note_item_time = (TextView) convertView.findViewById(R.id.customer_note_item_time);
            viewHolder.customer_note_item_tapes = (LinearLayout) convertView.findViewById(R.id.customer_note_item_tapes);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        if (TextUtils.isEmpty(item.description)) {
            viewHolder.customer_note_item_description.setVisibility(View.GONE);
        } else {
            viewHolder.customer_note_item_description.setText(item.description);
            viewHolder.customer_note_item_description.setVisibility(View.VISIBLE);
        }

        Date date = null;
        if (item.createTime != null) {
            date = DateUtils.parseTimestampInSecondToDate(item.createTime);
        } else if (item.lastActiveTime2 != null) {
            date = DateUtils.parseTimestampInSecondToDate(item.lastActiveTime2);
        }

        if (date != null) {
            viewHolder.customer_note_item_time.setText(DateUtils.dateTime2String(date, DateUtils.MM_DD_HH_MM_SS));
        }

        viewHolder.customer_note_item_rl_bound.setTag(position);
        RxView.clicks(viewHolder.customer_note_item_rl_bound)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    if (!NetUtils.isNetworkAvailable(mContext)) {
                        ToastUtil.showToast(mContext.getString(R.string.network_fail));
                        return;
                    }
                    int positionp = (Integer) viewHolder.customer_note_item_rl_bound.getTag();
                    Intent intent = new Intent(mContext, ActivityCustomerNote.class);
                    intent.putExtra(CustomerConstant.CustomerNote.UUID, mNotes.get(positionp).noteId);
                    intent.putExtra(CustomerConstant.CustomerNote.MODE, CustomerConstant.CustomerNote.MODE_EDIT);
                    intent.putExtra(CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
                    mContext.startActivity(intent);
                    ((Activity) mContext).overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                });

        viewHolder.customer_note_item_rl_bound.setOnLongClickListener(this);

        //更新上部标志
        if (posAndMonth.containsKey(position)) {
            viewHolder.sort_title_tv.setVisibility(View.VISIBLE);
            if (date != null) {
                viewHolder.sort_title_tv.setText((date.getYear() + 1900) + "年"
                        + (date.getMonth() + 1) + "月");
            }
        } else {
            viewHolder.sort_title_tv.setVisibility(View.GONE);
        }
        updateTapesForButtons(item, viewHolder.customer_note_item_tapes);
        return convertView;
    }

    TapeMessageView.TapeOperate mCallBack;

    private void updateTapesForButtons(CustomerNoteJson item, LinearLayout container) {
        if (mCallBack == null) {
            mCallBack = new TapeMessageView.TapeOperate() {
                @Override
                public void onTapeToPlay(TapeMessageView view, BeanCustomerTape tape, float progress) {
                    boolean isPlaying = false;
                    try {
                        isPlaying = mRecorderWrapper.isPlaying();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                        mRecorderWrapper = null;
                        mRecorderWrapper = RecorderWrapper.getInstance();
                    }

                    if (isPlaying) {
                        mRecorderWrapper.releasePlayer();
                    }
                    if (mRecorderWrapper != null) {
//                        mRecorderWrapper.playRecordFile(tape.getFilePath());
                        //TODO
                        mRecorderWrapper.playRecordFile(AttachmentUtil.netPathToLocalPath(tape.getFilePath(), CustomerConstant.Recorder.DIR_PATH));
                        mRecorderWrapper.setPlayerOnCompletionListener(view);
                    }
                }

                @Override
                public void onTapeToPause(TapeMessageView view, BeanCustomerTape tape, float progress) {
                    if (mRecorderWrapper != null) {
                        mRecorderWrapper.pausePlayRecordFile();
                    }
                }
            };
        }

        List<CustomerTapeJson> tapes = item.listCustomerNoteTape;
        deleteInvalidTapes(tapes);

        int childCount = container.getChildCount();
        if (tapes == null || tapes.size() == 0) {
            container.setVisibility(View.GONE);
        } else {
            container.setVisibility(View.VISIBLE);
            int tapeCount = tapes.size();
            for (int i = 0; i < childCount; i++) {
                if (i < tapeCount) {
                    TapeMessageView mTapeMessageView = (TapeMessageView) (((ViewGroup) container.getChildAt(i)).getChildAt(0));
                    mTapeMessageView.setVisibility(View.VISIBLE);
                    mTapeMessageView.update(CustomerConvertUtil.convertCustomerTapeJson2BeanCustomerTape(tapes.get(i)));
                    mTapeMessageView.setTapeOperate(mCallBack);
                    ((ViewGroup) mTapeMessageView.getParent()).setVisibility(View.VISIBLE);
                } else {
                    container.getChildAt(i).setVisibility(View.GONE);
                }
            }
        }
    }

    private void deleteInvalidTapes(List<CustomerTapeJson> tapes) {
        if (tapes != null) {
            ArrayList<CustomerTapeJson> tapesRet = new ArrayList<>();
            for (CustomerTapeJson tape : tapes) {
                if (!TextUtils.isEmpty(tape.filePath)) {
                    if (AttachmentUtil.isPathFromNet(tape.filePath)) {
                        tapesRet.add(tape);
                    } else {
                        if (new File(tape.filePath).exists()) {
                            tapesRet.add(tape);
                        }
                    }
                }
            }
            tapes.clear();
            tapes.addAll(tapesRet);
        }
    }

    private void updateTapes(EntityCustomerNote item, TextView textView) {
        ArrayList<BeanCustomerTape> tapes = uuidAndTapes.get(item.getUuid());
        if (tapes == null) {
            tapes = new ArrayList<>();
            tapes.addAll(mRecordManager.getBeanCustomerTapes(item.getUuid()));
            uuidAndTapes.put(item.getUuid(), tapes);
        }

        if (tapes == null) {
            textView.setText("");
        } else {
            float textSize = textView.getTextSize();
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            textView.setText(getSpannableString(tapes, DisplayUtil.sp2px(mContext, textSize)));
        }
    }

    private Drawable mTapeBg;

    private SpannableString getSpannableString(ArrayList<BeanCustomerTape> tapes, int textSize) {

        SpannableString msp;
        if (mTapeBg == null) {
            mTapeBg = this.mContext.getResources().getDrawable(R.drawable.bg_yellow_rect_hollow);
        }
        msp = new SpannableString("a");

        msp.setSpan(new ImageSpan(mTapeBg) {
            @Override
            public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y,
                             int bottom, Paint paint) {
                paint.setTypeface(Typeface.create("normal", Typeface.BOLD));
                paint.setTextSize(textSize);
                int len = Math.round(paint.measureText(text, start, end));
                getDrawable().setBounds(0, 0, len + 20, textSize + 4);//TODO
                super.draw(canvas, text, start, end, x, top, y, bottom, paint);
                paint.setColor(Color.BLUE);
                paint.setTypeface(Typeface.create("normal", Typeface.BOLD));
                paint.setTextSize(textSize);
                canvas.drawText(text.subSequence(start, end).toString(), x + 10, y, paint);
            }
        }, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        return msp;
    }

    private static class ViewHolder {
        TextView sort_title_tv;
        RelativeLayout customer_note_item_rl_bound;
        TextView customer_note_item_description;
        LinearLayout customer_note_item_tapes;
        TextView customer_note_item_time;
    }

    private MDEBTDialog mMenuDialog;

    private void popDeleteDialog(String noteUuid) {

        String[] menu_messages = new String[]{"删除此笔记？"};
        mMenuDialog = new MDEBTDialog.Builder(this.mContext)
                .setMessages(menu_messages)
                .setContentViewClickable(false)
                .setTitle("删除笔记")
                .setShowButtons(true)
                .setPositiveButton("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOneNote(noteUuid);
                    }
                })
                .create();
        mMenuDialog.show();
    }

    private void deleteOneNote(String noteUuid) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.deleteNoteById(noteUuid).compose(RxUtil.rxSchedulerHelper()).subscribe(getNoteDeleteSubscriber());
    }

    private Observer<CustomerNoteDetailJson> getNoteDeleteSubscriber() {

        return new Observer<CustomerNoteDetailJson>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CustomerNoteDetailJson customerNoteCRUDRetJson) {
                if (customerNoteCRUDRetJson == null) {
                    ToastUtil.showToast(mContext.getString(R.string.network_fail));
                    return;
                }
                if (customerNoteCRUDRetJson.error != null) {
                    ToastUtil.showToast(mContext.getString(R.string.network_fail));
                    return;
                }
                if (customerNoteCRUDRetJson.error == null) {
                    if (customerNoteCRUDRetJson.data == null) {
                        ToastUtil.showToast(mContext.getString(R.string.network_fail));
                        return;
                    } else {
                        ToastUtil.showToast("笔记删除成功");
                        EventBus.getDefault().post(new EntityCustomerNote());
                        EventBus.getDefault().post(new CustomerEvent());
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(mContext.getString(R.string.network_fail));
            }

            @Override
            public void onComplete() {

            }
        };
    }

    private boolean directToEditPageMode = true;

    @Override
    public boolean onLongClick(View v) {
        if (directToEditPageMode) {
            int position = (Integer) v.getTag();
            popDeleteDialog(mNotes.get(position).noteId);
            return true;
        }
        return true;
    }

}
